/**
 * @author tmh
 * @date 2024/10/24 17:07
 * @description 使用中心拓展法
 */
public class T5最长回文子串2 {

    public String longestPalindrome(String s) {
        //定义左右边界
        int start = 0;
        int end = 0;
        for (int i = 0; i < s.length(); i++) {
            //单字符拓展
            int len1 = expand(s, i, i);
            //双字符拓展
            int len2 = expand(s, i, i + 1);
            int maxLen = Math.max(len2, len1);
            if (end - start + 1 < maxLen) {
                start = i - (maxLen - 1) / 2;
                end = i + maxLen / 2;
            }
        }
        return s.substring(start, end + 1);
    }

    private int expand(String s, int l, int r) {
        while (l >= 0 && r < s.length() && (s.charAt(l) == s.charAt(r))) {
            l--;
            r++;
        }
        //返回长度
        return r - l - 1;
    }
}
